package com.example.lianguisystem.controller;

import com.example.lianguisystem.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/util")
public class UtilController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/queryVersion")
    public Result queryVersion(@RequestParam("version") String version, @RequestParam("appid") String appid, @RequestParam("inwan") String inWan, @RequestParam(value = "type",required = false) String type) {
        if (!"test".equals(type)) {
            type = "";
        }
        appid = appid + type;
        String updateVersion = (String) stringRedisTemplate.opsForHash().get(appid, "version");
        if (version.compareTo(updateVersion) >= 0) {
            return Result.success();
        }
//        String uri = "http://one.rainbowklgz.com:63/";
        String uri = "http://116.6.92.6:9900/dwonFile/";
        if (inWan.equals("inwan")) {
            uri = "http://192.168.0.192:63/";
        }
        String url = uri + stringRedisTemplate.opsForHash().get(appid, "url");
        String date = "" + stringRedisTemplate.opsForHash().get(appid, "date");
        if (version != null && !updateVersion.equals(version)) {
            Map<String, String> map = new HashMap<>();
            map.put("url", url);
            map.put("note", "版本" + updateVersion + "已发布于" + date + "，请更新");
            return Result.success(map);
        }
        return Result.success();
    }

    @PostMapping("/updateVersion")
    public Result changeVersion(@RequestParam("version") String version, @RequestParam("appid") String appid, @RequestParam("url") String url, @RequestParam("type") String type) {
        if (!type.equals("test")) {
            type = "";
        }
        appid = appid + type;
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String format = LocalDate.now().format(dtf);
        stringRedisTemplate.opsForHash().put(appid, "version", version);
        stringRedisTemplate.opsForHash().put(appid, "url", url);
        stringRedisTemplate.opsForHash().put(appid, "date", format);
        return Result.success();
    }
}
